package com.duan.servlet.user;

import com.duan.pojo.User;
import com.duan.service.user.UserService;
import com.duan.service.user.UserServiceImpl;
import com.duan.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userCode = req.getParameter("userCode");
        String password = req.getParameter("userPassword");

        UserService userService = new UserServiceImpl();
        User user = userService.loginService(userCode, password);


        if(user != null){//查有此人，可以登录
            //将用户的信息放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION, user);//尽量放在一个常量里面
            //跳转到内部主页
            System.out.println("===============================查有此人");
            resp.sendRedirect(req.getContextPath() + "/jsp/frame.jsp");
        }else{//查无此人，无法登录
            //转发回登录页面，顺带提示它，用户名或密码错误
            System.out.println("登录失败，回到登录页面");
            req.setAttribute("error", "用户名或者密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req, resp);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req, resp);
    }
}
